﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Newtonsoft.Json;

namespace Web
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { action = "Index", id = UrlParameter.Optional },
                namespaces:new[] { "Web.Controllers" }
            );
        }
    }

    /// <summary>
    /// JsonResult,驼峰式转换
    /// </summary>
    public class LowerCamelJsonResult : ActionResult
    {
        /// <summary>
        /// 目标对象
        /// </summary>
        public object Data { get; set; }

        /// <summary>
        /// 构造器
        /// </summary>
        public LowerCamelJsonResult() { }

        /// <summary>
        /// 构造器
        /// </summary>
        public LowerCamelJsonResult(object data)
        {
            this.Data = data;
        }

        /// <summary>
        /// 重写执行结果
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            //json对象命名小驼峰式转换
            var json = JsonConvert.SerializeObject(
                this.Data,
                Formatting.Indented,
                new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }
            );

            context.HttpContext.Response.Write(json);
        }
    }
}

